<?php session_start();
//Check login status. Send to login page if not logged in.
if(!isset($_SESSION['loggedIn'])){
	header('Location: StudentLogin.php');
}
//Grab info from password fields and grab student name
$old=$_POST['oldPassword'];
$new=$_POST['newPassword'];
$check=$_POST['newPasswordCheck'];
$student=$_SESSION['student'];
//Open the appropriate passwords file for the student's class
$file="../data/Classes/" . $_SESSION['class'] . "/passwords.txt";
$fr=fopen($file,'r');
$s=0;
//Store each line in an array
while(!feof($fr)){
	$array[$s]=trim(fgets($fr));
	$s++;
}
fclose($fr);
$i=0;
$found=1;
//Scan the array till the Student's name is found. Mark the position of the comma.
while ($i<$s && $found == 1){
	$str=$array[$i];
	$pos=stripos($str,",");
	$sub=substr($str,0,$pos);
	if(strcmp($student,$sub)==0){
		$value=substr($str,$pos+1);
		$found=0;
		$loc=$i;
	}
	$i++;
}
//Grab the string in the array field that comes after the aforementioned comma.
//Compare to the listed Old Password
if($found == 0){
	if(strcmp($old,$value) == 0){
		//Compare the new and confirm boxes
		if(strcmp($new,$check) == 0){
			$string=$sub . "," . $check;
			$array[$loc]=$string;
			$fr=fopen($file,'w');
			fclose($fr);
			$i=0;
			while($i<$s){
				file_put_contents($file,$array[$i],FILE_APPEND);
				if(!($i == $s-1)){
					file_put_contents($file,"\n",FILE_APPEND);
				}
				$i++;
			}
			echo "Password successfully changed. <br/> <a href=\"StudentAssignment.php\">Go back to main menu</a>";
		} else {
			echo "New password did not match confirmation. <br/> <a href=\"ChangePassword.php\">Go back and try again</a>";
		}
	} else { 
		echo "Incorrect Password<br/> <a href=\"ChangePassword.php\">Go back and try again</a>";
	}
}
?>